import { asyncRoutes, constantRoutes } from '@/router'
import { listRolePermission } from "@/api/rolePermission/rolePermission"
import { Message } from 'element-ui'
/* Layout */
import Layout from '@/layout'

/**
 * 判断是否有权限
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role.id))
  } else {
    return true
  }
}

/**
 * 根据角色过滤路由
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

/**
 * 动态路由处理【根据服务端获取的数据获取角色身份】
 */
export function asyncRoutesHandler(asyncRoutes) {
  return new Promise((resolve, reject) => {
    listRolePermission().then(response => {
      let result = asyncRoutes
      if (response) {
        response.forEach(element => {
          element.component = Layout
          const childrens = element.children.map(e => {
            return {
              path: e.component.lastIndexOf("/") === -1 ? e.component : e.component.substring(e.component.lastIndexOf("/") + 1),
              component: () => Promise.resolve(require(`@/views${e.component}`).default),
              meta: e.meta
            }
          })
          element.children = childrens
        })
        response.push({ path: '*', redirect: '/404', hidden: true })
        result = response
      }
      if (!result) {
        Message.error("获取菜单失败");
      }
      resolve(result)
    }).catch(error => {
      reject(error)
    })
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(async resolve => {
      // 动态路由处理
      
      const asyncRoutesResult = await asyncRoutesHandler(asyncRoutes)
      let accessedRoutes
      // 数据库设计，超级管理员账户id为1
      if (roles.map(element => element.id).includes('1')) {
        // 为超级管理员时，默认拥有全部权限
        accessedRoutes = asyncRoutesResult || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutesResult, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
